package com.example.blog_system.controller;

import com.example.blog_system.dto.ApiResponse;
import com.example.blog_system.entity.Tag;
import com.example.blog_system.service.TagService;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/tags")
public class TagController {

    @Autowired
    private TagService tagService;

    @PostMapping
    @PreAuthorize("isAuthenticated()")
    public ResponseEntity<ApiResponse<Tag>> createTag(@Valid @NotBlank @RequestParam String name) {
        Tag createdTag = tagService.createTag(name);
        return ResponseEntity.ok(ApiResponse.success("标签创建成功", createdTag));
    }

    @DeleteMapping("/{id}")
    @PreAuthorize("isAuthenticated()")
    public ResponseEntity<ApiResponse<Void>> deleteTag(@PathVariable Long id) {
        tagService.deleteTag(id);
        return ResponseEntity.ok(ApiResponse.success("标签删除成功"));
    }

    @GetMapping("/{id}")
    public ResponseEntity<ApiResponse<Tag>> getTag(@PathVariable Long id) {
        Tag tag = tagService.getTagById(id);
        return ResponseEntity.ok(ApiResponse.success("获取标签成功", tag));
    }

    @GetMapping("/name/{name}")
    public ResponseEntity<ApiResponse<Tag>> getTagByName(@PathVariable String name) {
        Tag tag = tagService.getTagByName(name);
        return ResponseEntity.ok(ApiResponse.success("获取标签成功", tag));
    }

    @GetMapping
    public ResponseEntity<ApiResponse<Page<Tag>>> getAllTags(
            @PageableDefault(sort = "name", direction = Sort.Direction.ASC) Pageable pageable) {
        Page<Tag> tags = tagService.getAllTags(pageable);
        return ResponseEntity.ok(ApiResponse.success("获取标签列表成功", tags));
    }
} 